package com.wang.demo.application.handler;

import com.wang.demo.protocol.message.GroupQuitRequestMessage;
import com.wang.demo.protocol.message.GroupQuitResponseMessage;
import com.wang.demo.service.GroupSession;
import com.wang.demo.service.factory.GroupSessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Set;

/**
 * @author: Jeffrey
 * @date: 2022/01/22/9:45
 * @description:
 */
@ChannelHandler.Sharable
public class GroupQuitHandler extends SimpleChannelInboundHandler<GroupQuitRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupQuitRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        String username = msg.getUsername();

        Set<String> members = GroupSessionFactory.getGroupSession().getMembers(groupName);
        if (members == null){
            ctx.writeAndFlush(new GroupQuitResponseMessage(false,"群聊不存在"));
        }else if (!members.contains(username)){
            ctx.writeAndFlush(new GroupQuitResponseMessage(false,"你不在群中无法退出！"));
        }else{
            ctx.writeAndFlush(new GroupQuitResponseMessage(true,"退群成功！"));
        }

    }
}
